<template>
  <div class="grid-box hfull">
    <div class="header">
      <div>样式</div>
       <el-button-group>
        <el-button size="small" type="primary" @click="plus">+</el-button>
        <el-button size="small">
          <Icon icon="mdi:searches" @click="openTemplate" />
        </el-button>
      </el-button-group>
    </div>
    <div class="content">
      <div v-for="(item, i) in dataList" class="flex justify-between">
        <CssItem v-model:name="item.name" v-model:value="item.value" class="w96%" />
        <ElButton type="danger" link @click="minus(i)" class="w4%">-</ElButton>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
  import { ElButton, ElButtonGroup } from 'element-plus';
  import { Icon } from '@/components/Icon';
  import { ref, watch } from 'vue';
  import { open } from '@/components/Popup';
  import CssTemplate from './CssTemplate.vue';
  import CssItem from './CssItem.vue';

  const props = defineProps<{modelValue?: Record<string, any>}>()
  const emits = defineEmits(['update:modelValue'])

  function init() {
    const style = props.modelValue
    if(!style) return []

    return Object.keys(style).map(name => ({name, value: style[name]}))
  }
  const dataList = ref(init())

  function openTemplate() {
    open({ title: '选择模板' }, CssTemplate, { onChoose } )
  }

  function onChoose(style: Record<string, any>) {
    for(const name in style) {
      const value = style[name]
      dataList.value.push({name, value})
    }
  }

  function plus() {
    dataList.value.push({name: '', value: ''})
  }

  function minus(i) {
    dataList.value.splice(i, 1)
  }

  let outter = false
  let inner = false
  watch(() => props.modelValue, () => {
    if(inner) {
      inner = false
      return
    }
    
    outter = true
    dataList.value = init()
  })

  watch(() => dataList.value, () => {
    if(outter) {
      outter = false
      return
    }

    inner = true
    console.log('ccchange==', dataList.value)
    const ret = {}
    for(const item of dataList.value) {
      ret[item.name] = item.value
    }
    emits('update:modelValue', ret)
  }, { deep: true })
</script>
<style lang="less" scoped>
  .grid-box {
    display: grid;
    grid-template-columns: minmax(0, 1fr);
    grid-template-rows: 35px minmax(0, 1fr);
    grid-template-areas: 'header' 'content';
  }
  .header {
    grid-area: header;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: antiquewhite;
    padding-left: 5px;
    padding-right: 5px;
  }
  .content {
    grid-area: content;
    padding: 5px;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
  }
</style>